package com.ufcg.lvc.server;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ufcg.lvc.client.GreetingService;

/**
 * 
 * The server side implementation of the RPC service.
 * 
 * @author Larissa Costa
 * 
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	private Conexao conexaoUsuario = new Conexao().getNewConexao();

	public String[] validaUsuarioSenha(String login, String senha) {
		String[] a = DataBase.getInstance().conectaUsuario(login, senha);
		try {
			if (a != null) {
				return a;
			} else {
				return null;
			}
		} catch (Exception erro) {
			return null;
		}
	}

	@Override
	public String getNomeUsuario(String login, String senha) {
		try {
			String sql = "select nome from usuario where login = '" + login
					+ "' and senha = '" + senha + "';";
			conexaoUsuario.executaConsulta(sql);
			if (conexaoUsuario.getResultSet().next()) {
				return conexaoUsuario.getResultSet().getArray(1).toString();
			}
		} catch (Exception erro) {
			System.out.println("Erro ao recuperar nome do usuário: " + erro);
		}
		return "";
	}

	@Override
	public boolean gravarRespostas(String titulo, String texto) {
		File dir1 = new File("Respostas - gabaritos");
		String t = titulo + ".txt";
		File arq = new File(dir1, t);
		if (!dir1.exists()) {
			dir1.mkdir();
		}
		try {
			arq.createNewFile();
			FileWriter fileWriter = new FileWriter(arq, false);
			PrintWriter printWriter = new PrintWriter(fileWriter);
			printWriter.println(texto);
			printWriter.flush();
			printWriter.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	// @Override
	// public boolean gravarResultadosDasProva(String titulo, String texto) {
	// File dir1 = new File("Respostas - gabaritos");
	// String t = titulo + ".txt";
	// File arq = new File(dir1, t);
	// if (!dir1.exists()) {
	// dir1.mkdir();
	// }
	// try {
	// arq.createNewFile();
	// FileWriter fileWriter = new FileWriter(arq, false);
	// PrintWriter printWriter = new PrintWriter(fileWriter);
	// printWriter.println(texto);
	// printWriter.flush();
	// printWriter.close();
	// return true;
	// } catch (IOException e) {
	// e.printStackTrace();
	// return false;
	// }
	// }

	@Override
	public String getDataAtual() {
		Date data = new Date(System.currentTimeMillis());
		DateFormat formatarDate = new SimpleDateFormat("dd.MM.yyyy");
		return (formatarDate.format(data));
	}

	@Override
	public String corrigirProvas(String nomeImagem, String formato) {
		Runtime r = Runtime.getRuntime();
		String saida = "";
		try {
			Process p = r
					.exec("C:\\Executavel\\Gabaritos.exe C:\\ServerArea\\txt\\RespostasGabarito1.txt 1 C:\\ServerArea\\img\\"
							+ nomeImagem
							+ " "
							+ formato
							+ " C:\\ServerArea\\txt\\GroundTruth.txt");
			// System.out.println("C:\\Executavel\\Gabaritos.exe C:\\ServerArea\\txt\\RespostasGabarito1.txt 1 C:\\Users\\Larissa Costa\\workspace-Android\\Teste_\\Teste_\\war\\"+nomeImagem+" "+formato+" C:\\ServerArea\\txt\\GroundTruth.txt");
			// Process p =
			// r.exec("C:\\Executavel\\Gabaritos.exe C:\\ServerArea\\txt\\RespostasGabarito1.txt 1 C:\\ServerArea\\img\\0ug7om184lnlqkf4arut bmp C:\\ServerArea\\txt\\GroundTruth.txt");
			// Local do executavel

			// C:\Users\Larissa Costa\Downloads\Documents\Visual Studio
			// 2010\Projects\Gabaritos\Debug
			InputStream in = p.getInputStream();
			BufferedInputStream buf = new BufferedInputStream(in);
			InputStreamReader inread = new InputStreamReader(buf);
			BufferedReader bufferedreader = new BufferedReader(inread);

			// Read the ls output
			String line = "--";
			int i = 2;
			while (i < 36) {
				line = bufferedreader.readLine();
				saida += line + "#---";
				if (i == 35) {
					gravarRespostas("Gabarito3", saida);
				}
				i++;
			}
			// Check for ls failure
			bufferedreader.close();
			inread.close();
			buf.close();
			in.close();
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
		return saida;
	}

}